package com.mbigger.admin.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonUtil {

	public final static boolean isJsonValid(String json) {
		if (StringUtils.isEmpty(json)) {
			return false;
		}
		try {
			final ObjectMapper mapper = new ObjectMapper();
			mapper.readTree(json);
			return true;
		} catch (IOException e) {
			return false;
		}
	}

	public final static String wrapperList(List<String> list, String root) {
		final ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put(root, list);
		String result = null;
		try {
			result = mapper.writeValueAsString(dataMap);
		} catch (JsonProcessingException e) {
			log.error(e.getMessage());
		}
		return result;
	}

	public final static String object2Json(Object object) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			log.error(e.getMessage());
			return null;
		}
	}

	public final static <T> T json2Object(String json, Class<T> valueType) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return (T) mapper.readValue(json, valueType);
		} catch (JsonParseException e) {
			log.error(e.getMessage());
			return null;
		} catch (JsonMappingException e) {
			log.error(e.getMessage());
			return null;
		} catch (IOException e) {
			log.error(e.getMessage());
			return null;
		}
	}

	public final static <T> List<T> json2List(String json, Class<T> valueType) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, valueType);
			@SuppressWarnings("unchecked")
			List<T> list = (List<T>) mapper.readValue(json, javaType);
			return list;
		} catch (JsonParseException e) {
			log.error(e.getMessage());
			return null;
		} catch (JsonMappingException e) {
			log.error(e.getMessage());
			return null;
		} catch (IOException e) {
			log.error(e.getMessage());
			return null;
		}
	}
}
